const Consul = require('consul')
const config = require('../config/dev')

class ConsulConfig {
    constructor() {
        this.consul = new Consul(config.consul);
    }

    /**
     *
     * @param name 服务名称
     * @param address 服务的地址
     * @param port 服务的端口
     * @param http 心跳检测地址
     * @param interval 心跳检测频率
     * @param timeout 超时时间
     * @param callback
     * @returns {Promise<void>}
     */
    async registerServer({name, address, port, check: {http, interval, timeout}}, callback) {
        this.consul.agent.service.register({name, address, port, check: {http, interval, timeout}}, (err, res) => {
            if (err) {
                callback(err, null);
            } else {
                callback(null, name + 'register success')
            }
        });
    }

    async getConfig(key) {
        return new Promise(((resolve, reject) => {
            this.consul.kv.get(key, (err, res) => {
                if (err) {
                    return reject(err);
                }
                if (!res) {
                    return reject(`${key} is not exists...`);
                }
                return resolve(JSON.parse(res.Value));
            });
        }))
    }

    // 更新 user 配置简单封装
    async setUserConfig(key, val, callback) {
        await this.getConfig('drea', (err, res) => {
            if (err) {
                callback(err, null);
            } else {
                if (!res) {
                    callback('drea is not exists...',null);
                }
                let value = JSON.parse(res.Value);
                console.log(value)
                value[key] = val;
                console.log(value)
                this.consul.kv.set(key, JSON.stringify(value), (err, res) => {
                    if (err) {
                        callback(err, null);
                    } else {
                        callback(null, res);
                    }
                })
            }
        });
    }
}

module.exports = ConsulConfig;
